#include <iostream>
#include <unistd.h>
#include <pthread.h>
using namespace std;

void *threadRoutine(void *args)
{
    const char *threadname=(char*)args;
    int cnt=0;
    while (true)
    {
        cout << threadname <<": "<< getpid() << pthread_self()<< endl;

        sleep(1);
        cnt++;

        if(cnt==5)break;
    }

    return (void*)1;
}

//线程tid转换为16进制
std::string toHex(pthread_t tid)
{
    char buf[64]={0};
    snprintf(buf,sizeof(buf),"%p",tid);

    return buf;
}

class Request
{
public:
    Request(int start,int end,const string &threadname)
        :_start(start)
         ,_end(end)
         ,_threadname(threadname)
    {}
    
    //计算函数
    int sum()
    {
        int ret=0;
        for(int i=_start;i<=_end;i++)
        {
            ret+=i;
            printf("%s is runing, caling... %d\n",_threadname.c_str(),i);

            usleep(100000);
        }

        return ret;
    }
public:
    int _start;
    int _end;
    string _threadname;
};

class Response
{
public:
   Response(int result,int exitcode)
       :_result(result)
        ,_exitcode(exitcode)
    {}
public:
    int _result;//计算结果
    int _exitcode;//验证结果是否有效
};

void* sumRoutine(void *args)
{
    Request *rq=static_cast<Request*>(args);

    Response *rs=new Response(0,0);
    rs->_result=rq->sum();
  
    delete rq;
    return rs;
}

int main()
{
    pthread_t tid;
    Request * rq=new Request(1,100,"thread 1");
    pthread_create(&tid,nullptr,sumRoutine,rq);//将类对象作为参数传递 
    
    void* ret;//接收线程返回值
    pthread_join(tid,&ret);
    
    Response* rsp=static_cast<Response*>(ret);
    printf("main thread wait success: %s , return result:%d\n",toHex(tid).c_str(),rsp->_result);
    
    delete rsp; 
    sleep(5);
    return 0;
}

//int main()
//{
//    pthread_t tid;
//    pthread_create(&tid, nullptr, threadRoutine,(void*)"thread 1");
//
//    void *ret;//接收线程返回值
//    while (true)
//    {
//        cout << "main thread: " << getpid() << endl;
//
//        sleep(1);
//
//        int n = pthread_join(tid,&ret);
//        if(n==0)
//        {
//            printf("thread wait success: , ret val: %d\n",(long long int)ret);//void* 指针64位下是8字节，必须强转为long long ，强转为int会发生截断
//            break;
//        }
//    }
//
//
//    return 0;
//}
